package com.example.config;

import com.example.entity.DroneData;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Configuration
public class WebsocketHandler extends TextWebSocketHandler {
    private static final Set<WebSocketSession> sessions = new HashSet<>();
    private ScheduledExecutorService scheduler;
    // 定义 ObjectMapper
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 添加新连接
        sessions.add(session);
        System.out.println("New connection established: " + session.getId());

        // 开始推送 CSV 数据
        startDataPush(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 收到消息时的处理逻辑
        System.out.println("Received message: " + message.getPayload());

        // 向所有连接的客户端推送消息
        for (WebSocketSession webSocketSession : sessions) {
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage("Server: " + message.getPayload()));
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 移除关闭的连接
        sessions.remove(session);
        System.out.println("Connection closed: " + session.getId());
    }

    // 推送消息给所有客户端
    public void broadcastMessage(String message) throws Exception {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));
            }
        }
    }

    private void startDataPush(WebSocketSession session) {
        scheduler = Executors.newScheduledThreadPool(1);

        try {
            // 使用 PathMatchingResourcePatternResolver 来获取所有以 "flight_track_" 开头的文件
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:flight_track_*.csv");

            // 创建 CSVReader 列表用于读取多个文件，同时为每个文件分配一个编号
            List<CSVReader> readers = new ArrayList<>();
            List<Integer> droneIds = new ArrayList<>();  // 对应每个文件的无人机编号
            int droneId = 1;

            for (Resource resource : resources) {
                InputStream inputStream = resource.getInputStream();
                CSVReader reader = new CSVReader(new InputStreamReader(inputStream));
                readers.add(reader);
                droneIds.add(droneId);  // 分配编号
                droneId++;

                // 跳过表头
                reader.readNext();
            }

            // 每秒推送所有文件的一行数据
            scheduler.scheduleAtFixedRate(() -> {
                try {
                    List<DroneData> droneDataList = new ArrayList<>();

                    // 遍历所有文件，每个文件读取一行
                    for (int i = 0; i < readers.size(); i++) {
                        CSVReader reader = readers.get(i);
                        String[] values = reader.readNext();

                        if (values != null) {
                            // 解析为经纬度和高度
                            double latitude = Double.parseDouble(values[0]);
                            double longitude = Double.parseDouble(values[1]);
                            double altitude = Double.parseDouble(values[2]);

                            // 将数据封装成 DroneData 对象，并添加无人机编号
                            DroneData droneData = new DroneData(droneIds.get(i), longitude, latitude, altitude);
                            droneDataList.add(droneData);
                        }
                    }

                    // 将所有文件的某一行数据打包成类数组，并发送给客户端
                    session.sendMessage(new TextMessage(objectMapper.writeValueAsString(droneDataList)));

                } catch (IOException | CsvException e) {
                    e.printStackTrace();
                }
            }, 0, 1, TimeUnit.SECONDS);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
